import copy
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from CloudGuardian.models import BindRelationship
from SecureHelperServer.settings import formatResponseData
from User.models import User
from utils.conf import Response, newID
from utils.custom import MyJWTAuthentication


class BindWardUserView(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = [MyJWTAuthentication]
    # 局部(本视图有效)权限类
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        用户之间建立监护关系
        """
        data = copy.deepcopy(formatResponseData)
        try:
            bindCode = request.data.get("bindCode")

            if not bindCode:
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            guardianUser = request.user

            wardUser = User.objects.filter(bindCode=bindCode).first()

            if not wardUser:
                return Response(data=data, responseMsg="监护码无效",
                                loggerMsg=f"用户之间建立监护关系：未找到监护码为{bindCode}的用户", isError=True)

            if wardUser.uid == guardianUser.uid:
                return Response(data=data, responseMsg="不能与自己建立监护关系",
                                loggerMsg=f"用户之间建立监护关系：不能与自己建立监护关系，uid={guardianUser.uid}",
                                isError=True)

            exists = BindRelationship.objects.filter(wardUser=wardUser, guardianUser=guardianUser).exists()

            if exists:
                return Response(data=data, responseMsg="该用户已跟您建立监护关系",
                                loggerMsg=f"用户之间建立监护关系：不能重复建立监护关系，guardianUserUid={guardianUser.uid}，wardUserUid={wardUser.uid}",
                                isError=True)

            # 建立监护关系
            bindRelationship = BindRelationship(id=newID(), wardUser=wardUser, guardianUser=guardianUser)
            bindRelationship.save()

            return Response(data=data, responseMsg="添加被监护人成功",
                            loggerMsg=f"用户之间建立监护关系：建立成功，guardianUserUid={guardianUser.uid}，wardUserUid={wardUser.uid}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
